package com.budwk.app.sqfwV2.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.sqfw.constants.SqfwCloudBusinessConstants;
import com.budwk.app.sqfw.dto.SqfwServiceRecordUpdateDTO;
import com.budwk.app.sqfw.dto.TransferServiceRecordDTO;
import com.budwk.app.sqfw.models.*;
import com.budwk.app.sqfw.services.*;
import com.budwk.app.sqfw.tencent.TCyysb;
import com.budwk.app.sqfw.vo.GenerateExcelUrlVO;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CompleteFlowExcelParamForController;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CompleteFlowPdfParamForController;
import com.budwk.app.sqfwDoc.codeGeneratorV2.generate.ResultOfExcelGenerator;
import com.budwk.app.sqfwDoc.dto.TemplateCodeUpdateDTO;
import com.budwk.app.sqfwV2.dto.dto.AuthenticRightDTO;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownExcelLedgerReqVo;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownFileTypesResVo;
import com.budwk.app.sqfwV2.dto.vo.SummaryQueryReqVo;
import com.budwk.app.sqfwV2.enums.AuthenticRightEnum;
import com.budwk.app.sqfwV2.enums.CaringStaffEnum;
import com.budwk.app.sqfwV2.service.baiyunqu.AuthenticRightExcelService;
import com.budwk.app.sqfwV2.service.baiyunqu.AuthenticRightPdfService;
import com.budwk.app.sqfwV2.service.baiyunqu.AuthenticRightV2ExcelService;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.poiUtils.CommonFormOfficeUtils;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import com.budwk.starter.common.openapi.annotation.ApiDefinition;
import com.budwk.starter.common.openapi.annotation.ApiFormParams;
import com.budwk.starter.common.openapi.annotation.ApiOperation;
import com.budwk.starter.common.openapi.annotation.ApiResponses;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.security.utils.SecurityUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@IocBean
@At("/platform/sqfw/authenticRight")
@ApiDefinition(tag = "白云区")
@Slf4j
public class AuthenticRightController {
    @Inject
    private AuthenticRightPdfService authenticRightPdfService;
    @Inject
    private SysUserService sysUserService;
    @Inject
    private HuaweiOssService huaweiOssService;
    @Inject
    private SqfwServicerecordService sqfwServicerecordService;
    @Inject
    private SqfwCloudcallbackService sqfwCloudcallbackService;
    @Inject
    private SqfwWorkorderService sqfwWorkorderService;
    @Inject
    private PropertiesProxy propertiesProxy;
    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;

    @Inject
    private SqfwCompleteflowService sqfwCompleteflowService;
    @Inject
    private AuthenticRightExcelService authenticRightExcelService;

    @Inject
    private AuthenticRightV2ExcelService authenticRightV2ExcelService;
    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "提交数据/生成PDF")
    @ApiFormParams(implementation = TemplateCodeUpdateDTO.class)
    @ApiResponses(implementation = GenerateExcelUrlVO.class)
    @SaCheckLogin
    @Aop(TransAop.READ_COMMITTED)
    public Result<?> submitCase(@Param("..") CompleteFlowPdfParamForController paramForController) {
        log.info("AuthenticRightController submitCase param: {}", JSONObject.toJSONString(paramForController));
        SqfwServiceRecordUpdateDTO sqfwServicerecord = BeanUtil.mapToBean(paramForController.getCustomerParam(),SqfwServiceRecordUpdateDTO.class,true);

        String userId = SecurityUtil.getUserId();
        Sys_user sysUser = sysUserService.fetch(userId);
        if (sysUser == null) return Result.error("当前登录用户错误,请重新登录");

        // wzy 2023-11-22 从后端查出用户数据进行赋值地级市5级数据
        sqfwServicerecord.setProvince(sysUser.getProvince());
        sqfwServicerecord.setCity(sysUser.getCity());
        sqfwServicerecord.setDistrict(sysUser.getDistrict());
        sqfwServicerecord.setCounty(sysUser.getCounty());
        sqfwServicerecord.setCommunity(sysUser.getCommunity());
        sqfwServicerecord.setCreatedBy(userId);
        String getPhone = sqfwServicerecord.getService_phone();
        sqfwServicerecord.setDelFlag(false);

        // 赋值关于语音时常相关属性
        if (!StringUtils.isNotBlank(sqfwServicerecord.getService_phone()) && sqfwServicerecord.getDuration() != null) {
            long audioDuration = sqfwServicerecord.getDuration() / 1000;
            sqfwServicerecord.setDuration(audioDuration);
            Date endTime = new Date(sqfwServicerecord.getConnect_time().getTime() + audioDuration);
            sqfwServicerecord.setEnd_time(endTime);
        }
        sqfwServicerecord.setRecording_text(sqfwServicerecord.getRecording_text());
        sqfwServicerecord.setService_phone(null);
        sqfwServicerecord.setService_name(null);
        sqfwServicerecord.setFinishStatus("new");

        // 处理语音转文字相关事情
        Sqfw_cloudcallback cloudCallBack = handleVideoTransTextAtServiceRecordCreate(sqfwServicerecord);

        Sqfw_servicerecord newServiceOrder = sqfwServicerecordService.insert(sqfwServicerecord);

        if (cloudCallBack != null) {
            cloudCallBack.setBusinessId(newServiceOrder.getId());
            sqfwCloudcallbackService.insert(cloudCallBack);
        }

        Result<String> result = Result.NEW();
        result.addData(sqfwServicerecord.getId());

        // 新增语音通话需要生成一个工单
        Sqfw_workorder workOrder = new Sqfw_workorder();
        workOrder.setSqfw_id(newServiceOrder.getId());
        workOrder.setUser_name(sysUser.getUsername());
        workOrder.setWk_grade("0");
        workOrder.setWk_priority("take_time_complete");
        workOrder.setUser_id(newServiceOrder.getCreatedBy());
        workOrder.setCreateDate(new Date());
        workOrder.setUpdatedAt(new Date());
        workOrder.setCreatedBy(newServiceOrder.getCreatedBy());
        // wzy 2023-5-25 服务记录生成工单的时候不主动完成对应工单
        workOrder.setWk_status("new");
        // workOrder.setComplete_time(new Date());
        workOrder.setDelflag(false);
        workOrder.setServiceType(sqfwServicerecord.getType());
        sqfwWorkorderService.insert(workOrder);

        if (StringUtils.isNotBlank(getPhone)) {
            List<String> strings = new ArrayList<>();
            TransferServiceRecordDTO dto = new TransferServiceRecordDTO();
            dto.setServiceRecordId(newServiceOrder.getId());
            List<String> list = Lists.newArrayList(getPhone.split(","));
            for (String str : list) {
                Sys_user querySysUser = sysUserService.getUserByLoginname(str);
                strings.add(querySysUser.getId());
            }
            dto.setToSysUserIdList(strings);
            sqfwWorkorderService.transferServiceRecordNew(dto);
        }
        //
        AuthenticRightDTO authenticRightDTO=JSON.parseObject(paramForController.getCompleteFlowDataDTO().getFormSummary().getParamData(), AuthenticRightDTO.class);

        if(null != authenticRightDTO.getDownFlag() && authenticRightDTO.getDownFlag().equals("否")){
            paramForController.getCompleteFlowDataDTO().getFormSummary().setFillDate(DateUtil.parse("0001-01-01 00:00:00.000"));
        }
        paramForController.getCompleteFlowDataDTO().getFormSummary().setSqfwId(sqfwServicerecord.getId());
        paramForController.getCompleteFlowDataDTO().getFormSummary().setWorkOrderId(workOrder.getId());
        paramForController.getCompleteFlowDataDTO().getCompleteFlow().setSqfwId(sqfwServicerecord.getId());
        paramForController.getCompleteFlowDataDTO().getCompleteFlow().setWorkerId(workOrder.getId());
        paramForController.getCompleteFlowDataDTO().getCompleteFlow().setText(StrFormatter.format("{}{}",authenticRightDTO.getCaseNumber(),authenticRightDTO.getNoticeType()));
        authenticRightPdfService.createPdfAndMsg(paramForController);

        return Result.data(sqfwServicerecord.getId());
    }


    @At
    @Ok("json:full")
    @POST
    @ApiOperation(name = "获取案件详情")
    @SaCheckLogin
    public Result<?> getCase(@Param("sqfwId") String sqfwId,@Param("caseType") String caseType) {
        Sqfw_formSummary_new sqfwFormSummaryNew=null;
        if(AuthenticRightEnum.A.getName().equals(caseType)){
             sqfwFormSummaryNew=  sqfwFormsummaryNewService.fetch(Cnd.where(Sqfw_formSummary_new::getSqfwId,"=",sqfwId)
                    .and("param_data->>'caseType'","=", AuthenticRightEnum.C.getName()).desc(Sqfw_formSummary_new::getCreateDate));
            if(ObjectUtil.isEmpty(sqfwFormSummaryNew)){
                sqfwFormSummaryNew=  sqfwFormsummaryNewService.fetch(Cnd.where(Sqfw_formSummary_new::getSqfwId,"=",sqfwId)
                        .and("param_data->>'caseType'","=", caseType).desc(Sqfw_formSummary_new::getCreateDate));
            }
        }else {
            if(ObjectUtil.isEmpty(sqfwFormSummaryNew)){
                sqfwFormSummaryNew=  sqfwFormsummaryNewService.fetch(Cnd.where(Sqfw_formSummary_new::getSqfwId,"=",sqfwId)
                        .and("param_data->>'caseType'","=", caseType).desc(Sqfw_formSummary_new::getCreateDate));
            }
        }
        if(ObjectUtil.isEmpty(sqfwFormSummaryNew)){
            return Result.data(new AuthenticRightDTO());
        }
        AuthenticRightDTO authenticRightDTO= JSON.parseObject(sqfwFormSummaryNew.getParamData(), AuthenticRightDTO.class);
        return Result.data(authenticRightDTO);
    }


    private Sqfw_cloudcallback handleVideoTransTextAtServiceRecordCreate(SqfwServiceRecordUpdateDTO serviceRecord) {
        if (StringUtils.isNotBlank(serviceRecord.getRecording_file())
                && !serviceRecord.getApp_type().equals("7")
                && !serviceRecord.getApp_type().equals("8")) {

            Boolean cloudTransFlag = serviceRecord.getCloudTransFlag();
            cloudTransFlag = cloudTransFlag == null;
            if (cloudTransFlag) {
                // 这里会进行语音识别 分为两个分支一个是调用腾讯的语音识别，另外一个是手机本地已经识别完成，然后直接使用
                String url = huaweiOssService.getPwdPath(serviceRecord.getRecording_file());

                String serviceIp = propertiesProxy.get("jarService.ip");
                String port = propertiesProxy.get("server.port");
                String callback = StrFormatter.format("http://{}:{}/platform/sqfw/cloudcallback/callback", serviceIp, port);
                Long taskId = TCyysb.Send(url, callback);

                if (taskId != null && taskId > 0L) {
                    serviceRecord.setTaskId(taskId.toString());
                }

                return null;
            } else {
                String localAudioTransText = serviceRecord.getLocalAudioTransText();
                String localAudioTransOriText = serviceRecord.getLocalAudioTransOriText();
                serviceRecord.setRecording_text(serviceRecord.getLocalAudioTransText());

                Sqfw_cloudcallback cloudCallBack = new Sqfw_cloudcallback();
                cloudCallBack.setAudioUrl(serviceRecord.getRecording_file());
                cloudCallBack.setText(localAudioTransText);  // 这个字段存已经通过系统替换过的文本
                cloudCallBack.setResultDetail(localAudioTransOriText);
                cloudCallBack.setBusinessId(serviceRecord.getId());
                cloudCallBack.setBusinessType(SqfwCloudBusinessConstants.SERVICE_RECORD);
                cloudCallBack.setCreatedAt(new Date().getTime());
                cloudCallBack.setUpdatedAt(new Date().getTime());
                cloudCallBack.setDelFlag(false);
                cloudCallBack.setTransChannel(SqfwCloudBusinessConstants.TRANS_CHANNEL_DFSJ);
                return cloudCallBack;
            }
        }

        return null;
    }


    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "提交数据/生成PDF")
    @ApiFormParams(implementation = TemplateCodeUpdateDTO.class)
    @ApiResponses(implementation = GenerateExcelUrlVO.class)
    @SaCheckLogin
    public Result<?> submitData(@Param("..") CompleteFlowPdfParamForController paramForController) {
        log.info("AuthenticRightController submitData param: {}", JSONObject.toJSONString(paramForController));
        authenticRightPdfService.createPdfAndMsg(paramForController);
        return Result.success();
    }


    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "提交数据/生成PDF")
    @SaCheckLogin
    public Result<?> dataLabel(@Param("sqfwId") String sqfwId) {
        List<String> label=new ArrayList<>();
        int a = sqfwFormsummaryNewService.count(Cnd.where(Sqfw_formSummary_new::getSqfwId,"=",sqfwId)
                .and("param_data->>'caseType'","=",AuthenticRightEnum.A.getName()));
        if(a>0){
            label.add("1");
        }
        int b = sqfwFormsummaryNewService.count(Cnd.where(Sqfw_formSummary_new::getSqfwId,"=",sqfwId)
                .and("param_data->>'caseType'","=",AuthenticRightEnum.B.getName()));
        if(b>0){
            label.add("2");
            label.add("5");
        }
        int c = sqfwFormsummaryNewService.count(Cnd.where(Sqfw_formSummary_new::getSqfwId,"=",sqfwId)
                .and("param_data->>'caseType'","=",AuthenticRightEnum.C.getName()));
        if(c>0){
            label.add("3");
            label.add("4");
        }
        return Result.data(label);
    }

    @At
    @Ok("json")
    @POST
    @SaCheckLogin
    public Result<?> generateDetailFile(@Param("..") SummaryQueryReqVo reqVo) {
        List<DownFileTypesResVo> downFileTypesResVos = new ArrayList<>();
        if(reqVo.getFillType().equals("12345确权")){
            reqVo.setQueryKey("('案件确权','会议协调')");
        }else {
            reqVo.setQueryKey("('实地回访')");
        }
        Dao dao =  NutzIocUtils.getBean(Dao.class);

        Sql sql2 = Sqls.fetchInt("select count(*)\n" +
                "from\n" +
                "\t(\n" +
                "\tselect\n" +
                "\t\trow_number() over (partition by sqfw_id\n" +
                "\torder by\n" +
                "\t\tfill_date desc) as rk ,\n" +
                "\t\t*\n" +
                "\tfrom\n" +
                "\t\tshequ.sqfw_form_summary_new\n" +
                "\twhere\n" +
                "\ttype ='12345确权' and param_data->>'caseType' in $castType and fill_date between '$fillStartDate 00:00:00' and '$fillEndDate 23:59:59' and create_by='$userId' ) t1\n" +
                "where\n" +
                "\tt1.rk = 1");
        sql2.setVar("fillStartDate",reqVo.getFillStartDate())
                .setVar("fillEndDate",reqVo.getFillEndDate())
                .setVar("userId",SecurityUtil.getUserId())
                .setVar("castType",reqVo.getQueryKey());
        dao.execute(sql2);
        Sql sql3 = Sqls.fetchInt("select count(*)\n" +
                "from\n" +
                "\t(\n" +
                "\tselect\n" +
                "\t\trow_number() over (partition by sqfw_id\n" +
                "\torder by\n" +
                "\t\tfill_date desc) as rk ,\n" +
                "\t\t*\n" +
                "\tfrom\n" +
                "\t\tshequ.sqfw_form_summary_new\n" +
                "\twhere\n" +
                "\ttype ='12345确权' and param_data->>'caseType' in $castType and fill_date between '$fillStartDate 00:00:00' and '$fillEndDate 23:59:59' and create_by='$userId' ) t1\n" +
                "where\n" +
                "\tt1.rk = 1");
        sql3.setVar("fillStartDate",reqVo.getFillStartDate())
                .setVar("fillEndDate",reqVo.getFillEndDate())
                .setVar("userId",SecurityUtil.getUserId())
                .setVar("castType","('会议协调')");
        dao.execute(sql3);
        int a = sql2.getInt();
        int b = sql3.getInt();
        AuthenticRightEnum[] values = AuthenticRightEnum.values();
        for (AuthenticRightEnum serviceEnum : values) {
            DownFileTypesResVo resVo = new DownFileTypesResVo();
            resVo.setPreviewImage(List.of(serviceEnum.getPreviewImage().split(",")))
                    .setFileCode(String.valueOf(serviceEnum.getCode()))
                    .setCreatedAt(System.currentTimeMillis())
                    .setFileTemplatePath(AuthenticRightEnum.getBlankTemplate(serviceEnum.getCode()))
                    .setLocation(serviceEnum.getCode());
            if(serviceEnum.getCode()==1){
                resVo.setFileName("案件确权/协调通知书")
                        .setFileType("pdf")
                        .setLabel("通知书");
                if(a>0){
                    resVo.setHiveData(true);
                }
            }else if(serviceEnum.getCode()==2){
                resVo.setFileName("12345案件实地回访表")
                        .setFileType("pdf")
                        .setLabel("回访表");
                if(a>0){
                    resVo.setHiveData(true);
                }
            } else if(serviceEnum.getCode()==3){
                resVo.setFileName("12345案件汇总表")
                        .setFileType("pdf")
                        .setLabel("合集,通知书,协调情况,确权表");
                if(b>0){
                    resVo.setHiveData(true);
                }
            }else if(serviceEnum.getCode()==4) {
                resVo.setFileName("会议协调情况台账")
                        .setFileType("excel")
                        .setLabel("台账,协调情况");
                if (b > 0) {
                    resVo.setHiveData(true);
                }
            }else if(serviceEnum.getCode()==5) {
                resVo.setFileName("12345案件实地回访表台账")
                        .setFileType("excel")
                        .setLabel("台账,回访表");
                if (a > 0) {
                    resVo.setHiveData(true);
                }
            }
            downFileTypesResVos.add(resVo);
        }
        Pagination pagination=new Pagination();
        pagination.setTotalCount(a);
        if(reqVo.getFillType().equals("12345确权")){
            downFileTypesResVos=downFileTypesResVos.stream().filter(s->s.getFileCode().equals("1")||
                    s.getFileCode().equals("3")||
                    s.getFileCode().equals("4")).collect(Collectors.toList());
        }else {
            downFileTypesResVos=downFileTypesResVos.stream().filter(s->s.getFileCode().equals("2")||
                    s.getFileCode().equals("5")).collect(Collectors.toList());
        }
        pagination.setList(downFileTypesResVos);
        return Result.data(pagination);
    }



    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "提交数据/生成PDF")
    @SaCheckLogin
    public Result<?> downPdfLedger(@Param("sqfwId")String sqfwId,@Param("code")Integer code,@Param("isDownTemplate")boolean isDownTemplate) {
        List<GenerateExcelUrlVO> generateExcelUrlVOS = new ArrayList<>();
        GenerateExcelUrlVO generateExcelUrlVO = new GenerateExcelUrlVO();
        generateExcelUrlVOS.add(generateExcelUrlVO);
        if (isDownTemplate) {
            generateExcelUrlVO.setExcelUrl(AuthenticRightEnum.getBlankTemplate(Integer.valueOf(code)));
        } else {
            Sqfw_formSummary_new formSummary1 = sqfwFormsummaryNewService.fetch(Cnd.where(Sqfw_formSummary_new::getSqfwId,"=",sqfwId)
                    .and("param_data->>'caseType'","=",AuthenticRightEnum.getName(code)).desc(Sqfw_formSummary_new::getCreateDate));

            if (ObjectUtil.isNotEmpty(formSummary1)) {
                Sqfw_completeflow  completeflow= sqfwCompleteflowService.fetch(Cnd.where(Sqfw_completeflow::getId, "=", formSummary1.getSqfwFlowId())
                        .and(Sqfw_completeflow::getResourcePath, "!=", "creating")
                        .and(Sqfw_completeflow::getResourcePath, "!=", "error"));
                if (ObjectUtil.isNotEmpty(completeflow)) {
                    generateExcelUrlVO.setExcelUrl(NutzIocUtils.getOssPrefix()+completeflow.getResourcePath());
                }
            }
        }
        return Result.data( generateExcelUrlVOS);
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "提交数据/生成PDF")
    @SaCheckLogin
    public Result<?> downPdfLedgerV2(@Param("..") DownExcelLedgerReqVo reqVo) {
        GenerateExcelUrlVO generateExcelUrlVO = new GenerateExcelUrlVO();
        Dao dao =  NutzIocUtils.getBean(Dao.class);
        Integer code=Integer.valueOf(reqVo.getFileCode());
        if (reqVo.isDownTemplate()) {
            generateExcelUrlVO.setExcelUrl(AuthenticRightEnum.getBlankTemplate(Integer.valueOf(code)));
        } else {
            Sql sql = Sqls.create("select *\n" +
                    "from\n" +
                    "\t(\n" +
                    "\tselect\n" +
                    "\t\trow_number() over (partition by sqfw_id\n" +
                    "\torder by\n" +
                    "\t\tfill_date desc) as rk ,\n" +
                    "\t\t*\n" +
                    "\tfrom\n" +
                    "\t\tshequ.sqfw_form_summary_new\n" +
                    "\twhere\n" +
                    "\ttype ='12345确权' and param_data->>'caseType' = '$castType' and fill_date between '$fillStartDate  00:00:00' and '$fillEndDate 23:59:59' and create_by='$userId' order by fill_date desc  ) t1\n" +
                    "where\n" +
                    "\tt1.rk = 1");
            sql.setCallback(Sqls.callback.entities());
            sql.setVar("fillStartDate",reqVo.getFillStartDate())
                    .setVar("fillEndDate", reqVo.getFillEndDate())
                    .setVar("userId",SecurityUtil.getUserId())
                    .setVar("castType",AuthenticRightEnum.getName(code));
            sql.setEntity(dao.getEntity(Sqfw_formSummary_new.class));
            dao.execute(sql);
            List<Sqfw_formSummary_new> formSummary1 = sql.getList(Sqfw_formSummary_new.class);
            if (CollectionUtil.isNotEmpty(formSummary1)) {
                List<String> sqfwFlowIdS = formSummary1.stream().map(Sqfw_formSummary_new::getSqfwFlowId).collect(Collectors.toList());
               List<Sqfw_completeflow>   completeflow= sqfwCompleteflowService.query(Cnd.where(Sqfw_completeflow::getId, "in", sqfwFlowIdS)
                        .and(Sqfw_completeflow::getResourcePath, "!=", "creating")
                        .and(Sqfw_completeflow::getResourcePath, "!=", "error"));
                if (CollectionUtil.isNotEmpty(completeflow)) {
                    List<String> pdfPathList = completeflow.stream().map(Sqfw_completeflow::getResourcePath).collect(Collectors.toList());
                    String url = CommonFormOfficeUtils.createConvergePdfAndUpload(pdfPathList, CaringStaffEnum.getFileName(code));
                    generateExcelUrlVO.setExcelUrl(url);
                }
            }
        }
        return Result.data(generateExcelUrlVO.getExcelUrl());
    }


    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "提交数据/生成PDF")
    @SaCheckLogin
    public Result<?> downExcelLedger(@Param("sqfwId")String sqfwId,@Param("code")Integer code,@Param("isDownTemplate")boolean isDownTemplate) {
        List<GenerateExcelUrlVO> generateExcelUrlVOS = new ArrayList<>();
        GenerateExcelUrlVO generateExcelUrlVO = new GenerateExcelUrlVO();
        generateExcelUrlVOS.add(generateExcelUrlVO);
        if (isDownTemplate) {
            generateExcelUrlVO.setExcelUrl(AuthenticRightEnum.getBlankTemplate(Integer.valueOf(code)));
        } else {
            CompleteFlowExcelParamForController paramForController=new CompleteFlowExcelParamForController();
            paramForController.setSqfwId(sqfwId);
            List<ExcelCreateConfig> excelCreateConfigList=new ArrayList<>();
            ExcelCreateConfig excelCreateConfig =  new ExcelCreateConfig();
            excelCreateConfig.setFileIdentity(String.valueOf(code));
            excelCreateConfigList.add(excelCreateConfig);
            paramForController.setExcelCreateConfigList(excelCreateConfigList);
            paramForController.setUserId(SecurityUtil.getUserId());
            List<ResultOfExcelGenerator> excel =  authenticRightExcelService.createExcel(paramForController);
            if (CollectionUtil.isNotEmpty(excel)) {
                generateExcelUrlVO.setExcelUrl(excel.get(0).getExcelUrl());
            }
        }
        return Result.data( generateExcelUrlVOS);
    }

    @At
    @Ok("json")
    @POST
    @SaCheckLogin
    public Result<?> downExcelLedgerV2(@Param("..") DownExcelLedgerReqVo reqVo) {
        GenerateExcelUrlVO generateExcelUrlVO = new GenerateExcelUrlVO();
        Integer code=Integer.valueOf(reqVo.getFileCode());
        if (reqVo.isDownTemplate()) {
            generateExcelUrlVO.setExcelUrl(AuthenticRightEnum.getBlankTemplate(Integer.valueOf(code)));
        } else {
            CompleteFlowExcelParamForController paramForController=new CompleteFlowExcelParamForController();
            NutMap map = NutMap.NEW();
            map.addv("fillStartDate",reqVo.getFillStartDate() + " 00:00:00")
                    .addv("fillEndDate",reqVo.getFillEndDate() + " 23:59:59");
            paramForController.setCustomerParam(map);
            List<ExcelCreateConfig> excelCreateConfigList=new ArrayList<>();
            ExcelCreateConfig excelCreateConfig =  new ExcelCreateConfig();
            excelCreateConfig.setFileIdentity(String.valueOf(code));
            excelCreateConfigList.add(excelCreateConfig);
            paramForController.setExcelCreateConfigList(excelCreateConfigList);
            paramForController.setUserId(SecurityUtil.getUserId());
            List<ResultOfExcelGenerator> excel =  authenticRightV2ExcelService.createExcel(paramForController);
            if (CollectionUtil.isNotEmpty(excel)) {
                generateExcelUrlVO.setExcelUrl(excel.get(0).getExcelUrl());
            }
        }
        return Result.data(generateExcelUrlVO.getExcelUrl());
    }

    @At
    @Ok("json")
    @POST
    @SaCheckLogin
    public Result<?> delData(@Param("sqfwId") String sqfwId) {
        sqfwFormsummaryNewService.clear(Cnd.where(Sqfw_formSummary_new::getSqfwId,"=",sqfwId).and(Sqfw_formSummary_new::getCreateBy,"=",SecurityUtil.getUserId()));
        sqfwCompleteflowService.clear(Cnd.where(Sqfw_completeflow::getSqfwId,"=",sqfwId).and(Sqfw_completeflow::getUserId,"=",SecurityUtil.getUserId()));
        return Result.success( );
    }



    @At
    @Ok("json")
    @POST
    public Result<?> list(@Param("pageNo") int pageNo,
                          @Param("pageSize") int pageSize,
                          @Param("sort") String sort,
                          @Param("fillDate") String fillDate,
                          @Param("castType") String castType) {
        Dao dao =  NutzIocUtils.getBean(Dao.class);
        Sql sql = Sqls.create("select\n" +
                "\t*\n" +
                "from\n" +
                "\t(\n" +
                "\tselect\n" +
                "\t\trow_number() over (partition by sqfw_id\n" +
                "\torder by\n" +
                "\t\tfill_date desc) as rk ,\n" +
                "\t\t*\n" +
                "\tfrom\n" +
                "\t\tshequ.sqfw_form_summary_new\n" +
                "\twhere\n" +
                "\ttype ='12345确权' and param_data->>'caseType' in $castType and $fill_date and create_by='$userId' order by fill_date desc ) t1\n" +
                "where\n" +
                "\tt1.rk = 1\n" +
                "limit $pageSize offset $pageNo");
        SqlExpressionGroup fillDateSql = new SqlExpressionGroup();
        Date date =  DateUtil.parseDate(fillDate+"-01");
        // 获取当月最后一天
        Date lastDayOfMonth = DateUtil.endOfMonth(date);
        fillDate = DateUtil.formatDate(lastDayOfMonth);
        // 输出当月最后一天的日期
        if ("desc".equals(sort)) {
            fillDateSql.andBetween(Sqfw_formSummary_new::getFillDate, "1970-01-01 00:00:00", fillDate + " 23:59:59");
        } else {
            fillDateSql.andBetween(Sqfw_formSummary_new::getFillDate, fillDate + " 23:59:59", new Date());
        }
        fillDateSql.setTop(false);
        sql.setCallback(Sqls.callback.entities());
        sql.setVar("fill_date",fillDateSql)
                .setVar("pageNo",(pageNo-1)*pageSize)
                .setVar("pageSize",pageSize)
                .setVar("userId",SecurityUtil.getUserId())
                .setVar("castType",castType);
        sql.setEntity(dao.getEntity(Sqfw_formSummary_new.class));
        dao.execute(sql);
        List<Sqfw_formSummary_new> dataList = sql.getList(Sqfw_formSummary_new.class);
        Pagination pagination = new Pagination();

        pagination.setPageNo(pageNo);
        pagination.setPageSize(pageSize);
        if(CollectionUtil.isNotEmpty(dataList)){
            pagination.setList(dataList);
            Sqfw_formSummary_new summaryNew = dataList.get(dataList.size()-1);
            // 查询当前月份的所有数据
            Date queryFillDate = summaryNew.getFillDate();
            queryFillDate = queryFillDate == null ? new Date() : queryFillDate;
            String fillDate2 = DateUtil.format(queryFillDate, DatePattern.NORM_MONTH_PATTERN);

            Sql sql2 = Sqls.fetchInt("select count(*)\n" +
                    "from\n" +
                    "\t(\n" +
                    "\tselect\n" +
                    "\t\trow_number() over (partition by sqfw_id\n" +
                    "\torder by\n" +
                    "\t\tfill_date desc) as rk ,\n" +
                    "\t\t*\n" +
                    "\tfrom\n" +
                    "\t\tshequ.sqfw_form_summary_new\n" +
                    "\twhere\n" +
                    "\ttype ='12345确权' and param_data->>'caseType' in $castType and fill_date between '$fillDate2-01 00:00:00' and '$fill_date 23:59:59' and create_by='$userId' ) t1\n" +
                    "where\n" +
                    "\tt1.rk = 1");
            sql2.setVar("fill_date",fillDate)
                    .setVar("fillDate2",fillDate2)
                    .setVar("userId",SecurityUtil.getUserId())
                    .setVar("castType",castType);
            dao.execute(sql2);
            pagination.setTotalCount(sql2.getInt());
        }

        return Result.data(pagination);
    }

    public static void main(String[] args) {
        try {
//            Date date= DateUtil.parseDate("2024-04-01");
//            String fillDateStr = DateUtil.format(date, DatePattern.NORM_MONTH_PATTERN);
//            YearMonth lastYearMonth = YearMonth.parse(fillDateStr);
//            int lastTotalDays = lastYearMonth.lengthOfMonth();
//            System.out.println(lastTotalDays);

            Date date =  DateUtil.parseDate("2024-04-01");
            // 获取当月最后一天
            Date lastDayOfMonth = DateUtil.endOfMonth(date);
            // 输出当月最后一天的日期
            System.out.println("当月最后一天的日期是：" + DateUtil.formatDate(lastDayOfMonth));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
